package com.byronspace.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ReadFromFile {
	private static String readFilePath = "F:/javaData/下雨天.txt";
	private static String writeFilePath = "F:/javaData/下雨天.json";
	private static List<Map<String, Object>> resultList  = new ArrayList<Map<String,Object>>();
	public static void main(String[] args) {	
		String str = ReadFromFile.readFileByLines(readFilePath);
		//str = "[{\"commentTime\":\"1492006621256\",\"nickName\":\"青风吹麦浪\",\"avatarUrl\":\"http://p1.music.126.net/TKwNDhxfAK6DU4PQUaFoUw==/18558656766988943.jpg\",\"userId\":\"281833904\",\"commentContent\":\"今年17年了，你们已经幸福的在一起了吧[可爱]\",\"likedCount\":\"1\"},{\"commentTime\":\"1490944860536\",\"nickName\":\"太无极13\",\"avatarUrl\":\"http://p1.music.126.net/VnZiScyynLG7atLIZ2YPkw==/18686200114669622.jpg\",\"userId\":\"293871871\",\"commentContent\":\"一年前，你给了我恋爱的感觉，我跟你表白后我开始了只属于自己的爱情。\n我给了自己一年的时间去成长，\n我第二次去追求爱情。我变了可是你没变。\n让我别花时间在没有结果的事情上。\n天下着雨，心流着泪，\n姐姐赞助我个冰激凌，\n让我把心冰冻下。\",\"likedCount\":\"3\"},{\"commentTime\":\"1491664023133\",\"nickName\":\"Gypsin\",\"avatarUrl\":\"http://p1.music.126.net/voJIgdC3Om6SImhwVfQyzA==/18509178743755324.jpg\",\"userId\":\"16136458\",\"commentContent\":\"有你的日子，去哪都可以\n沒 你 的 日 子，哪 都 不 想 去\",\"likedCount\":\"3\"},{\"commentTime\":\"1492007831098\",\"nickName\":\"我呀我就要\",\"avatarUrl\":\"http://p1.music.126.net/dQJmTL3bW2rOwsM61QE_lQ==/19040242858239323.jpg\",\"userId\":\"442952898\",\"commentContent\":\"准备2年了\",\"likedCount\":\"0\"},{\"commentTime\":\"1492007163950\",\"nickName\":\"BeanGaGa\",\"avatarUrl\":\"http://p1.music.126.net/gj-NR6aFWa-QxNC7_bQxcQ==/109951162867995063.jpg\",\"userId\":\"289593709\",\"commentContent\":\"初中时代\n\",\"likedCount\":\"0\"},{\"commentTime\":\"1490943993893\",\"nickName\":\"大揪揪的小揪揪\",\"avatarUrl\":\"http://p1.music.126.net/BVBPS6rb8IFBav3MRM2bjQ==/18928092672176795.jpg\",\"userId\":\"432264766\",\"commentContent\":\"现在结婚了吗\",\"likedCount\":\"2\"}]";		
		for(int i=0;i<resultList.size();i++){
			JSONObject commentObj = JSONObject.fromObject(resultList.get(i));
			String head = "{\"index\":{\"_index\":\"wangyimusic\",\"_type\":\"rainningDay\",\"_id\":"+i+"}}";
			writeLog(head);
			writeLog(commentObj.toString());
		}
		
	}

	/**
	 * 以行为单位读取文件，常用于读面向行的格式化文件
	 */
	@SuppressWarnings("finally")
	public static String readFileByLines(String fileName) {
		long start = System.currentTimeMillis();
		List<Map<String, Object>> commentMapList = new ArrayList<Map<String, Object>>();
		String result = "";
		File file = new File(fileName);
		BufferedReader reader = null;
		try {
			System.out.println("以行为单位读取文件内容，一次读一整行：");
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 0;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				Map<String, Object> commentMsg = new HashMap<String, Object>();
				Pattern pattern = Pattern.compile("^(\\d+)(.*)");
				Matcher matcher = pattern.matcher(tempString);
				String[] commentArr = tempString.split(" ");
				if (matcher.matches() && commentArr.length >= 6) {
					commentMsg.put("userId", Long.valueOf(commentArr[0]));
					commentMsg.put("nickName", commentArr[1]);
					commentMsg.put("avatarUrl", commentArr[2]);
					commentMsg.put("commentTime", Long.valueOf(commentArr[3]));
					commentMsg.put("likedCount", Long.valueOf(commentArr[4]));
					String temContent = "";
					for (int i = 5; i < commentArr.length; i++) {
						temContent += commentArr[i];
					}
					commentMsg.put("commentContent", temContent);
					commentMapList.add(commentMsg);

				} else {
					Map<String, Object> lastCommentMsg = commentMapList
							.get(commentMapList.size() - 1);
					String existContent = lastCommentMsg.get("commentContent").toString();
					lastCommentMsg.put("commentContent", existContent + "-/"
							+ tempString);
				}
				line++;
				System.out.println("line:"+line);
			}
			reader.close();
			resultList = removeDuplicate(commentMapList);
			JSONArray object = JSONArray.fromObject(resultList);
			result = object.toString();
			
			System.out.println("size:"+object.size());
			return result;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
			long end = System.currentTimeMillis();
			System.out.println("readFile-----------:start:"+start+";end:"+end+";during:"+(end-start));
			return result;
		}
		
	}

	public static void writeLog(String str) {
		long start = System.currentTimeMillis();
		try {
			File file = new File(writeFilePath);
			if (!file.exists())
				file.createNewFile();
			
			FileOutputStream out = new FileOutputStream(file, true); // 如果追加方式用true
			StringBuffer sb = new StringBuffer();
			sb.append(str + "\n");
			out.write(sb.toString().getBytes("utf-8"));// 注意需要转换对应的字符集
			out.close();
		} catch (IOException ex) {
			System.out.println(ex.getStackTrace());
		}
		long end = System.currentTimeMillis();
		System.out.println("writeLog-----------:start:"+start+";end:"+end+";during:"+(end-start));
	}
	public static void writeLog(String str,String saveFilePath) {
		long start = System.currentTimeMillis();
		try {
			File file = new File(saveFilePath);
			if (!file.exists())
				file.createNewFile();
			
			FileOutputStream out = new FileOutputStream(file, true); // 如果追加方式用true
			StringBuffer sb = new StringBuffer();
			sb.append(str + "\n");
			out.write(sb.toString().getBytes("utf-8"));// 注意需要转换对应的字符集
			out.close();
		} catch (IOException ex) {
			System.out.println(ex.getStackTrace());
		}
		long end = System.currentTimeMillis();
		System.out.println("writeLog-----------:start:"+start+";end:"+end+";during:"+(end-start));
	}
	public static List<Map<String, Object>> removeDuplicate(
			List<Map<String, Object>> list) {
		long start = System.currentTimeMillis();
		HashSet<Map<String, Object>> h = new HashSet<Map<String, Object>>(list);
		list.clear();
		list.addAll(h);
		long end = System.currentTimeMillis();
		System.out.println("removeDuplicate-----------:start:"+start+";end:"+end+";during:"+(end-start));
		return list;
	}
}
